<template>
  <div class="page-list-live">
    <PageList>
      <template #header>{{ title }}</template>
      <template #filter>
        <ListFilter
          :form="topFilter"
          :select-value="true"
          @changItemHandler="changHandler"
          @search="handleSearch"
          @reset="handleReset"
        ></ListFilter>
      </template>
      <template #tips>
        <el-button icon="el-icon-delete" type="danger" @click="batchDeletion">批量删除</el-button>
        <el-button icon="el-icon-edit" type="warning" @click="batchMarkRead">批量标记为已读</el-button>
        <el-button icon="el-icon-folder-remove" type="primary" @click="exportHandler">导出</el-button>
        <!-- <el-button icon="el-icon-folder-remove" type="primary" @click="unreadHandler">{{ unreadSwaitch ? '全部消息' : '未读消息' }}</el-button> -->
        <el-checkbox v-model="unreadSwaitch" style="margin-left: 20px" @change="unreadHandler">未读消息</el-checkbox>
      </template>
      <template #table>
        <ListTable
          ref="RefListTable"
          :loading="tableLoading"
          :table-data="tableData"
          :table-col="tableCol"
          @selectChange="handleSelectionChange"
        >
          <template slot="col1" slot-scope="stData">
            <div class="demo-image__preview">
              <el-image
                v-if="stData.row.file"
                style="width: 100px; height: 100px"
                :src="'data:image/jpg;base64,' + stData.row.file"
                :preview-src-list="['data:image/jpg;base64,' + stData.row.file]"
              ></el-image>
            </div>
          </template>
          <template slot="col2" slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              style="color: #e6a23c"
              :loading="scope.row.loadingDel"
              size="mini"
              type="text"
              @click="handleRowDel(scope.row)"
            >标记为已读</el-button>
          </template>
        </ListTable>
      </template>
    </PageList>
  </div>
</template>
<script>
import listMixin from '@/mixins/list'
import ListFilter from '@/components/ListFilter'
import { safetyCatTracking, alertOverMan, alertOverTime, alertSensor, alertVideo, area, alertHandler } from '@/api/api'
import { localhostUrl } from '@/utils/setUrl.js'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils'
export default {
  components: { ListFilter },
  mixins: [listMixin],
  data() {
    return {
      imgUrl: localhostUrl,
      title: '报警消息',
      selectValue: 5,
      // 临时图片
      url: '/files/20201017174207_singleHole.jpg',
      // 报警类型
      stateValue: null,
      // 标记为已读
      markReadList: {
        id: ''
      },
      deleteList: {
        id: ''
      },
      topFilter: {
        deptName: {
          label: '报警类型选择',
          placeholder: '请选择报警类型',
          type: 'select',
          arr: [
            { label: '环境监测报警', value: 1 },
            { label: '超员报警', value: 2 },
            { label: '超时报警', value: 3 },
            // { label: '视频报警', value: 4 },
            { label: '安全帽报警', value: 5 }
          ]
        },
        createdTime: { label: '时间', type: 'date', arr: ['createdTime', 'createdTime'] }
      },
      tableData: [],
      tableCol: [],
      areaData: [],
      unreadSwaitch: false
    }
  },
  watch: {
    stateValue: function (newValue, oldValue) {
      let that = this
      switch (newValue) {
        case 1:
          that.tableCol = [
            { type: 'selection' },
            { type: 'index', label: '序号', width: '60px' },
            {
              prop: 'createdTime',
              label: '报警时间',
              formatter: function (row, col, cell) {
                return this.$format(cell, true)
              }.bind(this),
              minWidth: '102px'
            },
            { prop: 'alertType', label: '报警类型' },
            // { prop: 'areaName', label: '区域' },
            // { prop: 'sensor.name', label: '设备名称' },
            // { prop: 'sensor.sensorStation.name', label: '基站名称' },
            // { prop: 'unit', label: '单位' },
            { prop: 'alertValue', label: '报警值' },
            { prop: 'settingValue', label: '设置值' },
            // { prop: 'unit', label: '单位' },
            // {
            //   prop: 'alertEndTime',
            //   label: '恢复时间',
            //   formatter: function (row, col, cell) {
            //     return this.$format(cell, true)
            //   }.bind(this),
            //   minWidth: '102px'
            // },
            {
              prop: 'Read',
              label: '状态',
              formatter: function (row, col, cell) {
                if (row.read == true) {
                  return '已读'
                } else {
                  return '未读'
                }
              }.bind(this),
              minWidth: '80px'
            },

            { label: '操作', custom: 'col2' }
          ]
          break
        case 2:
          that.tableCol = [
            { type: 'selection' },
            { type: 'index', label: '序号', width: '60px' },
            {
              prop: 'createdTime',
              label: '报警时间',
              formatter: function (row, col, cell) {
                return this.$format(cell, true)
              }.bind(this),
              minWidth: '62px'
            },
            { prop: 'alertType', label: '报警类型' },
            { prop: 'areaName', label: '区域' },
            { prop: 'limitationCount', label: '区域人数设定' },
            { prop: 'realCount', label: '报警人数' },
            { prop: 'overCount', label: '超出人数' },
            {
              prop: 'Read',
              label: '状态',
              formatter: function (row, col, cell) {
                if (row.read == true) {
                  return '已读'
                } else {
                  return '未读'
                }
              }.bind(this),
              minWidth: '80px'
            },
            { label: '操作', custom: 'col2' }
          ]
          break
        case 3:
          that.tableCol = [
            { type: 'selection' },
            { type: 'index', label: '序号', width: '60px' },
            {
              prop: 'createdTime',
              label: '报警时间',
              formatter: function (row, col, cell) {
                return this.$format(cell, true)
              }.bind(this),
              minWidth: '102px'
            },
            { prop: 'alertType', label: '报警类型' },
            { prop: 'areaName', label: '区域' },
            { prop: 'employee.name', label: '员工姓名' },
            { prop: 'employee.rfid', label: 'RFID' },
            { prop: 'employee.accessCardID', label: '门禁ID' },
            {
              prop: 'enterTime',
              label: '进入隧道时间',
              formatter: function (row, col, cell) {
                return this.$format(cell, true)
              }.bind(this),
              minWidth: '112px'
            },
            {
              prop: 'duration',
              label: '本次进场时长',
              formatter: function (row, col, cell) {
                return this.$formatHours(cell)
              }.bind(this),
              minWidth: '108px'
            },
            {
              prop: 'overTime',
              label: '超出时间',
              formatter: function (row, col, cell) {
                return this.$formatHours(cell)
              }.bind(this)
            },
            {
              prop: 'Read',
              label: '状态',
              formatter: function (row, col, cell) {
                if (row.read == true) {
                  return '已读'
                } else {
                  return '未读'
                }
              }.bind(this),
              minWidth: '80px'
            },
            { label: '操作', custom: 'col2' }
          ]
          break
        case 4:
          that.tableCol = [
            { type: 'selection', prop: '全选' },
            { type: 'index', label: '序号', width: '60px' },
            {
              prop: 'createdTime',
              label: '报警时间',
              formatter: function (row, col, cell) {
                return this.$format(cell, true)
              }.bind(this),
              minWidth: '102px'
            },
            { prop: 'alertType', label: '报警类型' },
            { prop: 'areaName', label: '区域' },
            { prop: 'deviceName', label: '设备名称' },
            { prop: 'eventType', label: '事件类型' },
            { prop: 'content', label: '事件描述信息' },
            {
              prop: 'Read',
              label: '状态',
              formatter: function (row, col, cell) {
                if (row.read == true) {
                  return '已读'
                } else {
                  return '未读'
                }
              }.bind(this),
              minWidth: '80px'
            },
            { label: '操作', custom: 'col2' }
          ]
          break
        case 5:
          that.tableCol = [
            { type: 'selection', label: '全选' },
            { type: 'index', label: '序号', width: '60px' },
            {
              prop: 'datetime',
              label: '抓拍时间',
              formatter: function (row, col, cell) {
                return this.$format(cell, true, true)
              }.bind(this),
              minWidth: '102px'
            },
            { prop: 'option', label: '抓拍功能项' },
            { prop: 'department', label: '所在区域' },
            { prop: 'deviceId', label: '抓拍设备名称' },
            { prop: 'file', label: '抓拍图像缩略图', custom: 'col1' },
            {
              prop: 'Read',
              label: '状态',
              formatter: function (row, col, cell) {
                if (row.read == true) {
                  return '已读'
                } else {
                  return '未读'
                }
              }.bind(this),
              minWidth: '80px'
            },
            { prop: 'code', label: '操作', custom: 'col2' }
          ]
          break

        default:
          break
      }

      let obj = this.serchObj
      obj.pageIndex = 1
      this.getList(obj)
    }
  },
  mounted() {
    let routeId = this.$route.query.id
    if (routeId) {
      this.stateValue = Number(routeId)
    } else {
      this.stateValue = 1
    }
    this.$store.dispatch('user/setDefult', this.stateValue)
  },
  beforeDestroy() {
    this.$store.dispatch('user/setDefult', 0)
  },
  methods: {
    unreadHandler(value) {
      this.unreadSwaitch = value
      this.getList(this.serchObj, this.unreadSwaitch)
    },
    // 导出
    async exportHandler() {
      try {
        let exportUrl = '' // 导出接口
        let exportName = '' // 导出表格名称
        switch (this.stateValue) {
          case 1:
            exportUrl = '/AlertSensor/ExcelFile'
            exportName = ' 环境监测报警'
            break
          case 2:
            exportUrl = '/AlertOverMan/ExcelFile'
            exportName = ' 超员报警'
            break
          case 3:
            exportUrl = '/AlertOverTime/ExcelFile'
            exportName = ' 超时报警'
            break
          case 4:
            exportUrl = '/AlertVideo/ExcelFile'
            exportName = ' 视频报警'
            break
          case 5:
            exportUrl = '/SafetyCatTracking/ExcelFile'
            exportName = ' 安全帽报警'
            break
        }
        let that = this
        let url = localhostUrl + exportUrl
        let xhr = new XMLHttpRequest()
        xhr.open('post', url, true)
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.setRequestHeader('Authorization', `Bearer ${getToken()}`)
        xhr.responseType = 'blob' // 返回类型blob  blob 存储着大量的二进制数据
        xhr.onload = function () {
          if (this.status === 200) {
            let blob = this.response
            let reader = new FileReader()
            reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
            reader.onload = function (e) {
              var a = document.createElement('a') // 转换完成，创建一个a标签用于下载
              a.download = parseTime(new Date(), '{y}-{m}-{d}') + exportName + '.xls'
              a.href = e.target.result
              document.body.appendChild(a) // 修复firefox中无法触发click
              a.click()
              document.body.removeChild(a)
            }
            alert('导出成功，请保存！')
          }
        }
        let str = JSON.stringify(this.serchObj)
        xhr.send(str) // 发送ajax请求
      } catch (err) {
        this.$message.error('导出失败！')
      }
    },
    // 获取区域
    async getArea(query) {
      try {
        const obj = query || { pageIndex: 1, pageSize: 10, orderBy: 'createdTime', orderByAscent: false }
        const {
          data: { items: resData, count, pageIndex }
        } = await area('post', obj, false)
        this.areaData = []
        this.areaData = resData.map(item => {
          item.loadingEdit = false
          item.loadingDel = false
          return item
        })
      } catch (err) {
        this.tableLoading = false
      }
    },
    // 下拉框改变
    changHandler(value) {
      if (value.key === 'deptName') {
        this.stateValue = value.val
      }
    },
    // 批量标记已读
    batchMarkRead() {
      if (this.markReadList.id == '') {
        this.$message('请选择要操作的项')
        return
      }
      this.$_showConfirm('此操作将标记报警消息为已读', () => {
        this.delMarkRead(this.markReadList)
      })
    },
    // 批量删除
    batchDeletion() {
      if (!this.deleteList.id) {
        this.$message.warning('请选择要删除的数据！')
        return
      }
      this.$_delConfirm('所选数据', () => {
        this.delMarkReadReq(this.deleteList)
      })
    },
    // 选中事件
    handleSelectionChange(event) {
      if (event.length > 0) {
        let ary = []
        event.forEach(item => {
          ary.push(item.id)
        })
        if (ary.length > 1) {
          this.deleteList.id = ary.join(',')
          this.markReadList.id = ary.join(',')
        } else {
          this.deleteList.id = ary[0]
          this.markReadList.id = ary[0]
        }
      } else {
        this.deleteList.id = ''
        this.markReadList.id = ''
      }
    },
    // 请求列表数据
    async getList(query) {
      if (query && query.search && query.search.length > 0) {
        let i = query.search.findIndex(item => {
          return item.key == 'deptName'
        })
        if (i > -1) {
          query.search.splice(i, 1)
        }
      }
      await this.getArea()
      this.tableLoading = true
      let that = this
      try {
        let obj = query || { pageIndex: 1, pageSize: 10, orderBy: 'createdTime', orderByAscent: false }
        if (this.unreadSwaitch) {
          if (obj.search && obj.search.length > 0) {
            obj.search.push({
              key: 'read',
              value: false,
              operation: 0,
              sequence: obj.search.length,
              relationship: 0
            })
          } else {
            obj.search = [
              {
                key: 'read',
                value: false,
                operation: 0
              }
            ]
          }
        } else {
          if (obj.search && obj.search.length > 0) {
            let i = obj.search.findIndex(item => {
              return item.key == 'read'
            })
            if (i > -1) {
              query.search.splice(i, 1)
            }
          }
        }
        let resValue = {}
        if (this.stateValue !== 5 && obj.search) {
          obj.search.forEach(item => {
            if (item.key === 'datetime') {
              item.key = 'createdTime'
            }
          })
        }
        switch (this.stateValue) {
          case 1:
            await alertSensor('post', obj, false).then(res => {
              that.setList(res, that)
            })
            break
          case 2:
            await alertOverMan('post', obj, false).then(res => {
              that.setList(res, that)
            })
            break
          case 3:
            await alertOverTime('post', obj, false).then(res => {
              that.setList(res, that)
            })
            break
          case 4:
            await alertVideo('post', obj, false).then(res => {
              that.setList(res, that)
            })
            break
          case 5:
            if (obj.search) {
              obj.search.forEach(item => {
                if (item.key !== 'datetime' && item.key !== 'read') {
                  item.key = 'datetime'
                }
              })
            }

            await safetyCatTracking('post', obj, false).then(res => {
              that.setList(res, that)
            })
            break

          default:
            // await safetyCatTracking('post', obj, false).then(res => {
            //   that.setList(res, that)
            // })
            break
        }
      } catch (err) {
        this.tableLoading = false
      }
    },
    // 给列表赋值
    setList(resValue, that) {
      const {
        data: { items: resData, count, pageIndex }
      } = resValue
      that.tableData = []
      that.tableData = resData.map(item => {
        item.loadingEdit = false
        item.loadingDel = false
        return item
      })
      this.tableData.forEach(item => {
        var i = this.areaData.findIndex(val => {
          return item.areaId == val.id
        })
        if (i > -1) {
          item.areaName = this.areaData[i].name
          // item.limitation = this.areaData[i].limitation
        }
      })

      that.$nextTick(() => {
        that.$refs['RefListTable'].update({ page: pageIndex, count })
        that.tableLoading = false
      })
    },
    // 批量标记已读
    async delMarkRead(row) {
      try {
        let type = 0
        switch (this.stateValue) {
          case 1:
            type = 1
            break
          case 2:
            type = 2
            break
          case 3:
            type = 3
            break
          // case 4:
          //   type = 1
          //   break
          case 5:
            type = 4
            break
        }
        await alertHandler(type, row.id)
        row.loadingDel = false
        await this.getList(this.serchObj)
        this.$message({
          type: 'success',
          message: '操作成功'
        })
      } catch (err) {
        row.loadingDel = false
      }
    },
    // 批量删除
    async delMarkReadReq(row) {
      try {
        let obj = { id: row.id, value: null }
        switch (this.stateValue) {
          case 1:
            await alertSensor('delete', obj, true)
            break
          case 2:
            await alertOverMan('delete', obj, true)
            break
          case 3:
            await alertOverTime('delete', obj, true)
            break
          case 4:
            await alertVideo('delete', obj, true)
            break
          case 5:
            await safetyCatTracking('delete', obj, true)
            break
        }
        row.loadingDel = false
        await this.getList(this.serchObj)
        this.$message({
          type: 'success',
          message: '操作成功'
        })
      } catch (err) {
        row.loadingDel = false
      }
    },
    handleRowDel(row) {
      row.loadingDel = true
      this.$_showConfirm(
        '报警消息将设为已读',
        () => {
          this.delMarkRead(row)
        },
        () => {
          row.loadingDel = false
        }
      )
    }
  }
}
</script>
